const { createApp, ref, reactive, onMounted, onBeforeUnmount, h } = Vue;
const weather = {
    '晴': './image/sunny.png',
    '多云': './image/cloudy.png',
    '阴': './image/overcast.png',
    '小雨': './image/rain.png',
    '中雨': './image/rain.png',
    '大雨': './image/rain.png',
    '暴雨': './image/rain.png',
    '小雪': './image/snow.png',
    '中雪': './image/snow.png',
    '大雪': './image/snow.png',
    '暴雪': './image/snow.png',
    '雷雨': './image/thunderstorm.png',
    '雾': './image/fog.png',
    '霾': './image/fog.png',
    '沙尘暴': './image/sandstorm.png',
}
const app = createApp({
    setup() {
        // eachrts
        let nightingaleEcharts, participantsEcharts, weeklyVisitorEcharts, mapChineseEcharts, jobWantedProbEcharts, mobileTalentsEcharts, regionalRankEcharts, jobWantedTrendEcharts, recruitTrendEcharts;

        onMounted(() => {
            window.addEventListener('resize', () => {
                let htmmlDom = document.getElementById("htmlFont");
                if (window.innerWidth <= 1500) return htmmlDom.style.fontSize = '15px';
                htmmlDom.style.fontSize = `${window.innerWidth / 100}px`
            })

            // 获取日期时间星期
            control.value = { ...control.value, ...getFormattedDateTime(Date.now()) };
            console.log(control.value)
            // 获取用户所在位置信息
            getLocation()

            // 基础数据获取
            getBasicData()
            // 人才结构
            handleNightingale()
            // 求职成功率
            handlejobWantedProb()

            // 地图
            modeMapChinese()
            // 人才流动排名
            handleMobileTalents()
            // 人才地区排名
            handleRegionalRank()
            // 职位需求趋势
            handleJobWantedTrend()
            // 招聘趋势
            handleRecruitTrend()

            // 行业热度
            handleParticipants()
            // 紧缺岗位
            handleWeeklyVisitor()
            // 监听窗口resize事件
            window.onresize = function () {
                // 左边
                nightingaleEcharts.resize();
                jobWantedProbEcharts.resize();
                // 中间
                mobileTalentsEcharts.resize();
                regionalRankEcharts.resize();
                mapChineseEcharts.resize();
                jobWantedTrendEcharts.resize();
                recruitTrendEcharts.resize();
                // 右边
                participantsEcharts.resize();
                weeklyVisitorEcharts.resize();
            };
            // console.log(getFormattedDateTime(Date.now()))
            // control.value.today = new Date().Format("yyyy.MM.dd");
            // control.value.currentTime = new Date().Format("HH:mm");
        })
        onBeforeUnmount(() => {
            window.removeEventListener('resize', () => {
                let htmmlDom = document.getElementById("htmlFont");
                if (window.innerWidth <= 1500) return htmmlDom.style.fontSize = '15px';
                htmmlDom.style.fontSize = `${window.innerWidth / 100}px`
            })
            // 定时器获取当前时间
            if (intervalKey) return clearInterval(intervalKey), intervalKey = null;
            intervalKey = setInterval(() => { control.value.currentTime = new Date().Format("HH:mm"); }, 1000)
        })
        // 最中间的地图
        const mapChineseList = ref({
            personneTotal: 728196389,
            yesterdayNum: 123,
            chainRatio: 12,
            // 地图排行默认值
            mapRankRegion: '北京',
            mapRanking: '10',
            mapRankPersonnel: '13421',
        });
        // 中间统计数值
        const statisticsList = ref([])
        // 参与率统计
        const personne = ref([])
        // 专业热度
        const courseSortList = ref([])
        // 囯岗位热度排名
        const teacherSortList = ref([])
        // 学校的列表
        const schoolList = ref([])
        // 课后风采
        const classPresentation = ref([])
        // 定时器键
        let intervalKey = null;
        // header数据
        const control = ref({
            currentTime: '',
            today: '',
            dayOfWeek: '',
            casts: [],
            // 热门行业头
            // numOfIndust: '',
            // hottestIndustry: '',
        })
        // 基础数据获取
        const getBasicData = () => {
            setTimeout(() => {
                // 中间统计数值
                statisticsList.value = [
                    { num: 111111, statisticsType: '课后服务总收费（元）' },
                    { num: 222222, statisticsType: '学校参与率（%）' },
                    { num: 333333, statisticsType: '学生参与数（人）' },
                    { num: 444444, statisticsType: '教师参与数（人）' },
                    { num: 555555, statisticsType: '特色课程数（节）' }
                ]
                // 参与率统计
                personne.value = [
                    { rate: 70, label: '全校学生', num: 200 },
                    { rate: 90, label: '全校教师', num: 20 },
                    { rate: 68, label: '学生基础', num: 180 },
                    { rate: 75, label: '校内教师', num: 18 },
                    { rate: 44, label: '学生特色', num: 130 },
                    { rate: 50, label: '校外教师', num: 13 }
                ]
                // 专业热度
                courseSortList.value = [
                    { coursName: '体能', feedbackScore: 1, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 2, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 3, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 4, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 5, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 6, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 7, applauseRate: 80 },
                    { coursName: '体能', feedbackScore: 8, applauseRate: 80 },
                ]
                // 囯岗位热度排名
                teacherSortList.value = [
                    { teacherName: '余英瑞', feedbackScore: 1, applauseRate: 80, sex: 'M' },
                    { teacherName: '余英瑞', feedbackScore: 2, applauseRate: 80, sex: 'F' },
                    { teacherName: '余英瑞', feedbackScore: 3, applauseRate: 80, sex: 'M' },
                    { teacherName: '余英瑞', feedbackScore: 4, applauseRate: 80, sex: 'F' },
                    { teacherName: '余英瑞', feedbackScore: 5, applauseRate: 80, sex: 'M' },
                    { teacherName: '余英瑞', feedbackScore: 6, applauseRate: 80, sex: 'F' },
                    { teacherName: '余英瑞', feedbackScore: 7, applauseRate: 80, sex: 'M' },
                    { teacherName: '余英瑞', feedbackScore: 8, applauseRate: 80, sex: 'F' }
                ]
                // 学校的列表
                schoolList.value = [
                    { label: '东湖小学', value: 1 },
                    { label: '西湖小学', value: 2 },
                    { label: '南湖小学', value: 3 },
                    { label: '北湖小学', value: 4 },
                ]
                control.value.school1 = schoolList.value[0].value;
                control.value.school2 = schoolList.value[0].value;

                // 课后风采
                classPresentation.value = [
                    { id: 1, image: './image/image.png' },
                    { id: 2, image: './image/image.png' },
                    { id: 3, image: './image/image.png' },
                    { id: 4, image: './image/image.png' },
                    { id: 5, image: './image/image.png' },
                    { id: 6, image: './image/image.png' },
                ]
            }, 1000)
        }
        // 获取当前时间
        const getCurrentTime = () => {
            control.value.currentTime = new Date().Format("yyyy-MM-dd HH:mm:ss");
        }
        // 
        const getLocation = () => {
            // 高德定位
            var geolocation = new AMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认为true
                timeout: 10000, // 超过10秒后停止定位，默认：无穷大
            });
            geolocation.getCurrentPosition(async function (status, result) {
                console.log(status, result)
                if (status === 'complete') {
                    // 成功获取位置
                    const {lat, lng} = result.position;
                    const geocodeUrl = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${lng},${lat}&key=f351fad35a447f5cba791c5412a330b1`;
                    control.value.casts = await getWeatherPROMISE(geocodeUrl);
                } else {
                    console.error(result)
                }
            });
            // 浏览器自带定位
            if ("geolocation" in navigator) {
                // Geolocation API可用
                navigator.geolocation.getCurrentPosition(async function (position) {
                    console.log(position)
                    // 成功获取位置
                    const { latitude, longitude } = position.coords;
                    var geocodeUrl = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=f351fad35a447f5cba791c5412a330b1`;
                    control.value.casts = await getWeatherPROMISE(geocodeUrl);
                }, function (error) {
                    // 获取位置失败
                    console.error("获取位置失败: " + error.message);
                });
            } else {
                // Geolocation API不可用
                console.log("Geolocation API不可用");
            }
        }

        // 人才结构
        const handleNightingale = () => {
            // Nightingale.series[0].data = [
            //     { value: 140, name: '机构教师1' },
            //     { value: 303, name: '志愿者1' },
            //     { value: 280, name: '其他2' },
            //     { value: 22, name: '校外教师1' }
            // ]
            // Nightingale.series[1].data = []
            nightingaleEcharts = echarts.init(document.getElementById('nightingale'));
            nightingaleEcharts.setOption(Nightingale);
        }
        // 求职成功率
        const handlejobWantedProb = () => {
            jobWantedProbEcharts = echarts.init(document.getElementById('jobWantedProb'))
            jobWantedProbEcharts.setOption(JobWantedProb);
        }

        /**
         * 中间四个
         */
        // 人才流动排名
        const handleMobileTalents = () => {
            const eachrtsMess = {
                title: ['浙江', '江苏', '广东', '上海', '北京', '四川', '湖北'],
                data: [
                    { value: 124 }, { value: 103 }, { value: 182 }, { value: 221 }, { value: 120 }, { value: 191 }, { value: 318 }
                ]
            }
            mobileTalentsEcharts = echarts.init(document.getElementById('mobileTalents'))
            mobileTalentsEcharts.setOption(MobileTalents(eachrtsMess))
        }
        // 人才地区排名
        const handleRegionalRank = () => {
            const data = [
                { value: 1048, name: '浙江', rato: '68%' },
                { value: 735, name: '重庆', rato: '30%' },
                { value: 580, name: '陕西', rato: '50%' }
            ]
            regionalRankEcharts = echarts.init(document.getElementById('regionalRank'))
            regionalRankEcharts.setOption(RegionalRank(data))
        }

        // 地图
        const modeMapChinese = () => {
            const mapList = [
                                '北京市', '天津市', '上海市', '重庆市', '河北省', '河南省', '云南省', '辽宁省', '黑龙江省', '湖南省', '安徽省', '山东省', '新疆维吾尔自治区', 
                                '江苏省', '浙江省', '江西省', '湖北省', '广西壮族自治区', '甘肃省', '山西省', '内蒙古自治区', '陕西省', '吉林省', '福建省', '贵州省', '广东省', 
                                '青海省', '西藏自治区', '四川省', '宁夏回族自治区', '海南省', '台湾省', '香港特别行政区', '澳门特别行政区', '南海诸岛'
                            ];
            const mapData = mapList.map((name, index) => ({ 
                name, value: randomData(), sort: ++index,
                // 默认选中
                selected: name == '北京市' ? true : false
            }));
            // 默认数据
            mapChineseList.value = {
                ...mapChineseList.value, 
                ...{
                    mapRanking: 1,
                    mapRankPersonnel: 318,
                    mapRankRegion: '北京市',
                }
            }
            mapChineseEcharts = echarts.init(document.getElementById('mapChinese'));
            mapChineseEcharts.showLoading();
            echarts.registerMap('china', chinaJONS);
            mapChineseEcharts.hideLoading();
            mapChineseEcharts.setOption(siteMapChinese(mapData));
            // 地图点击选中事件
            mapChineseEcharts.on('click', function (params) {
                const { name, value, sort } = params.data;
                console.log('地图点击', params);
                mapChineseList.value.mapRankRegion = name;
                mapChineseList.value.mapRanking = sort;
                mapChineseList.value.mapRankPersonnel = value;
                
                // console.log('地图点击', params);
                mapChineseEcharts.dispatchAction({
                    type: 'select',
                    seriesIndex: params.dataIndex,
                    name: params.name
                });
            })
        }
        const getBoxNum = (num) => {
            const spanNum = num.toString().split('');
            let domNum = '';
            spanNum.forEach((item, index) => { domNum += `<span class="numBox">${item}</span>` })
            return domNum;
        }

        // 职位需求趋势
        const handleJobWantedTrend = () => {
            jobWantedTrendEcharts = echarts.init(document.getElementById('jobWantedTrend'))
            jobWantedTrendEcharts.setOption(JobWantedTrend)
        }
        // 招聘趋势
        const handleRecruitTrend = () => {
            recruitTrendEcharts = echarts.init(document.getElementById('recruitTrend'))
            recruitTrendEcharts.setOption(RecruitTrend)
        }

        // 行业热度
        const handleParticipants = () => {
            const eachrtsMess = {
                title: ['AI', '新能源', '云计算', '军工', '航天', '无人机', '芯片'],
                data: [
                    { value: 213 }, { value: 513 }, { value: 321 }, { value: 124 }, { value: 232 }, { value: 123 }, { value: 421 }
                ]
            }
            control.value.numOfIndust = 65;
            control.value.hottestIndustry = 'AI';
            participantsEcharts = echarts.init(document.getElementById('participants'))
            participantsEcharts.setOption(Participants(eachrtsMess))
        }
        // 紧缺岗位
        const handleWeeklyVisitor = () => {
            const eachrtsMess = {
                title: ['AI', '新能源', '云计算', '军工'],
                data: [
                    { value: 124 }, { value: 353 }, { value: 321 }, { value: 412 }
                ]
            }
            weeklyVisitorEcharts = echarts.init(document.getElementById('weeklyVisitor'))
            weeklyVisitorEcharts.setOption(WeeklyVisitor(eachrtsMess))
        }
        
        // 退出重置数据
        onBeforeUnmount(() => {
            clearInterval(intervalKey);
            intervalKey = null;
        })
        return {
            statisticsList,
            personne,
            courseSortList,
            teacherSortList,
            schoolList,
            classPresentation,
            control,
            intervalKey,

            mapChineseList,
            // 天气
            weather,

            // 处理方法
            getBoxNum
        }
    }
})
app.use(ElementPlus); //全局引入element组件，mount之前调用
app.mount("#app");